﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Configuration;
using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;
using System.Runtime.Serialization;
using org.ids_adi.iring.utility;
using System.IO;

namespace DataLayerUnity
{

  public class ServiceProvider : IGuysAndGals
  {
    IDTOLayer dtoLayer = null;
    IUnityContainer container = null;

    public ServiceProvider()
    {
      Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);

      container = new UnityContainer();      
      UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");      
      section.Containers.Default.Configure(container);

      //container.Configure<InjectedMembers>()
      //  .ConfigureInjectionFor<IDTOLayer>(new InjectionConstructor(container, appName)); 
    }

    public string GetData(string applicationName)
    {
      try
      {
        ApplicationConfig applicationConfig = Utility.Read<ApplicationConfig>(@"Profiles\19610_ROB\" + applicationName + @"\Configuration.xml", true);

        container.RegisterInstance<ApplicationConfig>(applicationConfig);

        dtoLayer = container.Resolve<IDTOLayer>(applicationConfig.dtoLayerName);
        
        return dtoLayer.GetData();        
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    public ApplicationConfig WriteConfig(string applicationName)
    {
      try
      {
        ApplicationConfig applicationConfig = new ApplicationConfig() 
        {
          applicationName = applicationName,
          dataLayerName = "GalsDataLayer",
          dtoLayerName = "MonikaDTOLayer"
        };

        Utility.Write<ApplicationConfig>(applicationConfig, @"Profiles\19610_ROB\" + applicationName + @"\Configuration.xml", true);

        return applicationConfig;
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }
  }

  [DataContract]
  public class ApplicationConfig
  {
    [DataMember]
    public string applicationName { get; set; }

    [DataMember]
    public string dataLayerName { get; set; }

    [DataMember]
    public string dtoLayerName { get; set; }

    [DataMember]
    public string entitiesName { get; set; }
  }
}
